import { ChangeDetectionStrategy, Component, OnInit } from '@angular/core';
import { FormControl, Validators, FormGroup, FormBuilder, ValidatorFn } from '@angular/forms';
import { OptionItem, MessageService } from '@iux/live';

@Component({
  templateUrl: './basic.component.html',
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class BasicComponent implements OnInit {
  data: OptionItem[];
  formGroup: FormGroup;
  loading = false;
  disabledFlag = true;
  btnText = 'Enable';
  constructor(
    private fb: FormBuilder,
    private message: MessageService,
  ) {}

  ngOnInit(): void {
    this.data = this.initData();
    this.initForm();
  }

  initData(): any {
    return [
      {
        label: 'email',
        isLeaf: true,
      },
      {
        label: 'phone',
        isLeaf: true,
      },
    ];
  }

  initForm(): void {
    this.formGroup = this.fb.group({
      age: [{ value: '通过formControlName实现灰化', disabled: true }],
      password: ['', Validators.required],
      contact: ['email', Validators.required],
      gender: ['male', Validators.required],
      status: [['item002', 'item004']],
      description: [''],
      hobbies: [[], this.validHobbies()],
    });
    this.onContactChange('email');
  }

  // 自定义校验
  validHobbies(): ValidatorFn {
    return (control: FormControl): { [key: string]: any } => (control.value?.length > 3 ? { maxOverflow: true } : null);
  }

  reset(): void {
    this.formGroup.reset({
      password: '',
      contact: 'email',
      description: '',
      gender: 'male',
      status: [],
    });
    this.onContactChange('email');
  }

  register(): void {
    for (const i of Object.keys(this.formGroup.controls)) {
      this.formGroup.controls[i].markAsDirty();
      this.formGroup.controls[i].updateValueAndValidity();
    }
    // 判断校验，完成校验进行下一步操作
    if (!this.formGroup.invalid) {
      this.message.success('Next...');
    }
  }

  onContactChange(value): void {
    if (value === 'email') {
      const ctrl = new FormControl('', [Validators.required, Validators.maxLength(10)]);
      this.formGroup.addControl('email', ctrl);
      this.formGroup.removeControl('phone');
    } else if (value === 'phone') {
      const ctrl = new FormControl('', [Validators.required, Validators.maxLength(10)]);
      this.formGroup.addControl('phone', ctrl);
      this.formGroup.removeControl('email');
    }
  }

  change(): void {
    this.disabledFlag = !this.disabledFlag;

    if (this.disabledFlag) {
      this.btnText = 'Enable';
    } else {
      this.btnText = 'Disable';
    }

    const ageControl = this.formGroup.get('age');
    if (ageControl.disabled) {
      ageControl.enable();
    } else {
      ageControl.disable();
    }
  }
}
